# -*- coding: utf-8 -*-
import sys

import json

from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.shortcuts import render

from bsfault.commen.interface import page, DateEncoder, md5
from bsfault.models import user, log

reload(sys)
sys.setdefaultencoding('utf8')


# 用户登录
def userlogin(request):
    username = request.POST.get("username")
    pwd = request.POST.get("password")
    userResult = user.objects.filter(username=username, password=md5(pwd))
    if len(userResult) <= 0:
        log(log=username + "登陆失败").save()
        return render(request, "login.html", {'tip': "fail"})
    request.session['username'] = username
    request.session['identity'] = user.objects.filter(username=username).values('identity')[0]['identity']
    log(log=username + "登陆成功").save()
    return HttpResponseRedirect('/index/')


def userlist_data(request):
    if request.GET.get('seachuser') == '':
        J_data = page(user.objects.all().values(), request.GET.get('limit'), request.GET.get('offset'))

    else:
        J_data = page(user.objects.filter(username__contains=request.GET.get('seachuser')).values(), request.GET.get(
            'limit'), request.GET.get('offset'))
    for asset in J_data["data"]:
        J_data["response_data"]['rows'].append(
            {"id": asset['id'],
             "username": asset['username'], "identity": asset['identity'],
             "email": asset['email'], "tel": asset['tel']})
    return HttpResponse(json.dumps(J_data["response_data"], cls=DateEncoder))


# 验证用户名
def check_username(request):
    username = request.GET.get('username')
    if len(user.objects.filter(username=username)):
        return JsonResponse({"valid": False})
    else:
        return JsonResponse({"valid": True})


'''
添加用户
'''


def adduser(request):
    if request.method == 'POST':
        user_name = request.POST["username"]
        pwd = request.POST["pass"]
        identity = request.POST["identity"]
        email = request.POST["email"]
        tel = request.POST["tel"]
        user(username=user_name, password=md5(pwd), identity=identity, email=email, tel=tel).save()
        log(log=request.session.get('username') + "添加用户" + user_name).save()
        return HttpResponse(1)
    else:
        return HttpResponse(0)


# 删除用户
def deleteuser(request):
    log(log=request.session.get('username') + "删除用户-" +
            user.objects.filter(id=request.GET.get('id')).values('username')[0]['username']).save()
    user.objects.filter(id=request.GET.get('id')).delete()
    return HttpResponse(0)


# 修改用户
def update_user(request):
    if request.method == 'GET':
        id = request.GET["user_id"]
        email = request.GET["email"]
        tel = request.GET["tel"]
        log(log=request.session.get('username') + "修改用户" +
                user.objects.filter(id=request.GET.get('user_id')).values('username')[0]['username'] + '的信息').save()
        user.objects.filter(id=id).update(email=email, tel=tel)
        return HttpResponse(1)
    else:
        return HttpResponse(0)


# 修改密码
def update_pass(request):
    if request.method == 'GET':
        oldpass = request.GET["oldpass"]
        newpass = request.GET["newpass"]
        username = request.GET["username"]
        userResult = user.objects.filter(username=username, password=md5(oldpass))
        if len(userResult) <= 0:
            return HttpResponse(-1)
        user.objects.filter(username=username).update(password=md5(newpass))
        log(log=username + '修改了密码').save()
        del request.session['username']
        return HttpResponse(1)
    else:
        return HttpResponse(0)


# 重置密码
def rest_pass(request):
    log(log=request.session.get('username') + '重置了'+user.objects.filter(id=request.GET.get('id')).values('username')[0]['username']+'密码').save()
    user.objects.filter(id=request.GET.get('id')).update(password=md5(user.objects.filter(id=request.GET.get(
        'id')).values('username')[0]['username']))
    return HttpResponse(1)


# 用户登录页面
def login(request):
    return render(request, "login.html")


# 用户退出
def login_out(request):
    del request.session['username']
    return render(request, "login.html")


# 用户列表
def userlist(request):
    return render(request, 'userlist.html')


# 欢迎页
def welcome(request):
    return render(request, 'welcome.html')


# 主页
def index(request):
    return render(request, 'index.html',
                  {'user': request.session.get('username'), 'identity': request.session.get('identity')})

